<?php

namespace Laoha\Blog\Admin\Controllers;

use Laoha\Blog\Models\LaohaBlog;
use App\Admin\Controllers\AppBaseController;
use App\Admin\Forms\Grid;   //有分类，且分类设置允许自定义时，不使用use Encore\Admin\Grid是为了指定分类再新建;
use Encore\Admin\Layout\Content;
use Encore\Admin\Form;
use Encore\Admin\Show;
use Illuminate\Support\Facades\Auth;

class LaohaBlogController extends AppBaseController
{
    /**
     * Title for current resource.
     *
     * @var string
     */
    protected $name = 'laoha_blog';


    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
		if($cate_id = request('cate_id',0)){
			$app = get_app_cate($this->app,$cate_id);			
		}else{
			$app = get_app($this->app);
		}

		$app_sets = $app['sets'] ?? [];
		$grid = new Grid(new LaohaBlog());
		//列表前应用关联附加内容before_grid		
		foreach($app_sets['tabs'] as $k=>$x){   //$k = cate; $x=exts.cate.*			
			$tempclass = config("exts.{$k}.ext") ?? '';
			if( $x && $tempclass && class_exists($tempclass) && method_exists($tempclass,'before_grid') ){
				(new $tempclass())->before_grid($grid,$app);
			}
		}

		//回收站系列
		$trashed=request('trashed',0);
		if($trashed){
			$grid->model()->onlyTrashed();
			$grid->actions(function ($actions) {  // 添加恢复单位操作
				$actions->append(new \App\Admin\Actions\Tools\RestoreAct($actions->getKey())); 
			});

			$grid->actions(function ($actions) {
				$actions->disableDelete();
			});
		}
		$grid->tools(function ($tools){
			$tools->append(new \App\Admin\Actions\Tools\Trashed());
			if(request('trashed')){
				$tools->batch(function (\Encore\Admin\Grid\Tools\BatchActions $batch) {
					$batch->add('批量恢复', new \App\Admin\Actions\Tools\BatchRestore());
				});
			}
		});

        $grid->column('images', get_app_field_name($app,'images'))->style('width:50px')->display(function (){
			//dump($this->images);
					if($this->images){
						return "<img src='/upload/small/".$this->images[0]."' width='40' height='30' />";
					}else{
						return "<img src='/upload/small/nopic.jpg' width='40' height='30' />";
					}
				});
        $grid->column('title', get_app_field_name($app,'title'))->style('max-width:50%');
        $grid->column('user.name', __('责任人'));
        $grid->column('created_at', get_app_field_name($app,'created_at'));


		//关联附加内容grid()
		foreach($app_sets['tabs'] as $k=>$x){
			$tempclass = config("exts.{$k}.ext") ?? '';
			if( $x && $tempclass && class_exists($tempclass) && method_exists($tempclass,'grid') ){
				(new $tempclass())->grid($grid,$app);
			}
		}


		if(!empty($app['grid_selectors'])){
			$grid->selector(function (\Encore\Admin\Grid\Tools\Selector $selector) use($app){
				foreach($app['grid_selectors'] as $k=>$sel){
					$scope = $sel['scope'];
					if(!empty($sel['one'])){
						$selector->selectOne($k, $sel['title'], $sel['option'],function($query, $value) use($scope){
							return $query->$scope($value);
						});			
					}else{
						$selector->select($k, $sel['title'], $sel['option'],function($query, $value) use($scope){
							return $query->$scope($value);
						});						
					}
				}

			});
		}
        return $grid;
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     * @return Show
     */
    protected function detail($id)
    {
        $show = new Show(LaohaBlog::findOrFail($id));

        $show->field('id', __('Id'));
        $show->field('user_id', __('User id'));
        $show->field('cate_id', __('Cate id'));
        $show->field('title', __('Title'));
        $show->field('desc', __('Desc'));
        $show->field('content', __('Content'));
        $show->field('parse', __('Parse'));
        $show->field('image', __('Image'));
        $show->field('pos', __('Pos'));
        $show->field('group', __('Group'));
        $show->field('created_at', __('Created at'));
        $show->field('updated_at', __('Updated at'));

        return $show;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
		$form = new Form(new LaohaBlog);

		$app = get_app($this->app);
		if($form->isEditing() && !empty($this->id)){				
			$rs = LaohaBlog::find($this->id);
			if(!empty($app['sets']['has_cate_sets']) && !empty($rs->cate_id)){
				$app = get_app_cate($app,$rs->cate_id);
			}
			$app['id'] = $this->id;
		}elseif($cate_id = request('cate_id',0)){
			$app = get_app_cate($app,$cate_id);
		}
		$app_sets = $app['sets'] ?? [];
		

		
//dd($app_sets);
		//附加表须有before_form()
		foreach($app_sets['tabs'] as $k=>$x){ 
			$tempclass = config("exts.{$k}.ext") ?? '';
			if( $x && $tempclass && class_exists($tempclass) && method_exists($tempclass,'before_form') ){
				(new $tempclass())->before_form($form,$app);
			}
		}
		
        $form->hidden('user_id')->default(Auth::guard('admin')->user()->user_id);

        $form->text('title', get_app_field_name($app,'title'))->required();
		if($app_sets['app']['editor']=='md'){
			$form->textarea('content', get_app_field_name($app,'content'))->help($app_sets['app']['editor']);
		}elseif($app_sets['app']['editor']=='text'){
			$form->textarea('content', get_app_field_name($app,'content'))->help($app_sets['app']['editor']);
		}else{
			$form->textarea('content', get_app_field_name($app,'content'))->help($app_sets['app']['editor']);
		}
		$form->hidden('parse', $app_sets['app']['editor']);

        //$form->image('image', get_app_field_name($app,'image'));

		if(!empty($app_sets['app']['need']['images'])){
			if($app_sets['app']['need']['images']==2){
				$form->multipleImage('images', get_app_field_name($app,'images'))->removable()->sortable()->required();
			}else{
				$form->multipleImage('images', get_app_field_name($app,'images'))->removable()->sortable();
			}
		}

		if(!empty($app_sets['app']['need']['video'])){
			if($app_sets['app']['need']['video']==2){
				$form->url('video', get_app_field_name($app,'video'))->required();
			}else{
				$form->url('video', get_app_field_name($app,'video'));
			}
		}
		if(!empty($app_sets['app']['need']['link'])){
			if($app_sets['app']['need']['link']==2){
				$form->url('link', get_app_field_name($app,'link'))->required();
			}else{
				$form->url('link', get_app_field_name($app,'link'));
			}
		}

		//附加表须有form()
		foreach($app_sets['tabs'] as $k=>$x){ 
			$tempclass = config("exts.{$k}.ext") ?? '';
			if( $x && $tempclass && class_exists($tempclass) && method_exists($tempclass,'form') ){
				(new $tempclass())->form($form,$app);
			}
		}		
        $form->datetime('created_at',get_app_field_name($app,'created_at'))->format('YYYY-MM-DD HH:mm:ss');

        return $form;
    }

    public function restore()
    {
        $ids = request('ids');
		if(!is_array($ids)) $ids = str2arr($ids);
		LaohaBlog::onlyTrashed()->find($ids)->each->restore();
    }
}
